# Figure 7 Gini indices (aggregate)
y <- seq(1989,2022,by = 3)

# Average impute results in each year

# Gini index 
# multivariate Gini
g <- unlist(sapply(1:length(y),function(i){Reduce("+",lapply(1:5, function(k){agg[[i]][[k]]$Gini}))/5}))

# univariate Ginis
g_i <-sapply(1:length(y),function(i){
                  Reduce("+",lapply(1:5, function(k){
                    Gini(scf89_22[[i]][[k]][,4],scf89_22[[i]][[k]][,1])}))/5
                  })
g_w <-sapply(1:length(y),function(i){
  Reduce("+",lapply(1:5, function(k){
    df <- scf89_22[[i]][[k]][,c(5,1)]
    colnames(df) <- c("wealth","weight")
    df <- aggregate(weight~wealth, data = df, sum)
    df <- df[df$wealth>0,]
    Gini(df$wealth,df$weight)}))/5
})

#Kendall's tau
ktau <- sapply(1:length(y),function(i){
  Reduce("+",lapply(1:5,function(k){
    cor.test(scf89_22[[i]][[k]][,4],scf89_22[[i]][[k]][,5], method="kendall")$estimate
    }))/5
})

G <- data.frame(c(y),g,g_w,g_i,ktau)
names(G) <- c("Year","Gini","gw","gi","kt")
sz <- 1
szp <- 4.5
gini_plot <- ggplot(G) + 
  geom_line(aes(x=Year, y = Gini), size = sz, color = "#997700") + annotate("label", x=2016.5, y=0.71, label= "Income-Wealth", family = 'serif',color ="#997700",size = 7) +
  geom_point(aes(x=Year, y = Gini),pch =16 ,size = szp, color = "#997700") +
  geom_line(aes(x=Year, y = gw),size = sz, color = "#004488") + annotate("label", x=2016.5, y=0.78, label= "Wealth",family = 'serif', color = "#004488",size = 7) +
  geom_point(aes(x=Year, y = gw),pch =17 ,size = szp, color = "#004488") +
  geom_line(aes(x=Year, y = gi),size = sz, color = "#bb5566") + annotate("label", x=2016, y=0.56, label= "Income",family = 'serif', color ="#bb5566",size = 7) +
  geom_point(aes(x=Year, y = gi),pch =15 ,size = szp, color = "#bb5566")+
  geom_line(aes(x=Year, y = kt), size = sz, color = "black",linetype = 2) + annotate("label", x=2016.5, y=0.67, label=  expression(paste("Kendall's ", tau)),family = 'serif', color ="black",size =7) +
  theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5),
        panel.background = element_rect(fill = 'white'),
        panel.grid = element_blank(),
        panel.grid.major.y = element_line(color = "gray"),
        panel.grid.minor.y = element_line(color = "gray"),
        legend.position="none",
        text = element_text(family = "serif",size=22)) + ylab("Gini Index") +
      scale_x_continuous(breaks = y[y%%2==0],labels = y[y%%2==0])
ggsave(plot = gini_plot, width = 8, height = 6, filename = "fig7.png")